﻿using Microsoft.AspNetCore.Mvc;
using MyFramework.Core.Encrypt;
using MyFramework.OpenApi.BaiduTranslate;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace MyFramework.Plugins.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class BaiduController : ControllerBase
    {
        /// <summary>
        /// 百度翻译
        /// </summary>
        /// <param name="q"></param>
        /// <returns></returns>
        [HttpGet]
        [HttpPost]
        public string Translate(string q)
        {
            //// 原文
            //string q = "苹果";
            //// 源语言
            string from = "zh";
            // 目标语言
            string to = "en";
            try
            {
                if (string.IsNullOrEmpty(q))
                {
                    return q;
                }
                Dictionary<string, string> keyValues = new Dictionary<string, string>()
                {
                    ["q"] = q,
                    ["from"] = from,
                    ["to"] = to
                };
                string apiName = "translate";
                string responseBody = OpenApiHelper.Instance().Get(apiName, keyValues);
                responseBody = UnicodeHelper.Decode(responseBody);
                dynamic _data = Newtonsoft.Json.JsonConvert.DeserializeObject<dynamic>(responseBody);
                return _data.trans_result[0].dst.Value;
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }
    }
}
